package cc.io24.knewcafe.boss.config;

import com.netflix.client.ClientRequest;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Random;

public class CustomRule extends RoundRobinRule {

    @Override
    public Server choose(Object o) {
        return choose(getLoadBalancer(), o);
    }

    public Server choose(ILoadBalancer lb, Object key) {
        List<Server> servers = getLoadBalancer().getReachableServers();
        for (Server server : servers) {
            System.out.println(server.getId() + " id:" + server.getMetaInfo().getInstanceId());
            ThreadLocal<String> threadLocal = new ThreadLocal<>();
            String id = (String) RequestContext.getCurrentContext().get("server");
            if (StringUtils.equals(id, server.getMetaInfo().getInstanceId())) {
                return server;
            }
        }
        return servers.get(new Random().nextInt(servers.size()));
    }
}
